﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Fierce.Core.Aop;
using Fierce.Entity.Basic;

namespace Fierce.Core.Service.Basic
{
    public partial class BasicMenuFunctionService : OrderService<BasicMenuFunction>
    {
        public virtual ServiceResult SetFunction(string menuId, string[] functionIds)
        {
            var bmfs = db.BasicMenuFunction.Query(m => m.MenuID == menuId).ToList();
            var contains = bmfs.Where(m => functionIds.Contains(m.FunctionID));
            var noContains = bmfs.Where(m => !functionIds.Contains(m.FunctionID));

            db.BasicMenuFunction.Deleted(noContains);

            for (int i = 0; i < functionIds.Length; i++)
            {
                string functionid = functionIds[i];

                if (!string.IsNullOrEmpty(functionid))
                {
                    var entity = contains.FirstOrDefault(m => m.FunctionID == functionid);

                    if (entity == null)
                    {
                        entity = new BasicMenuFunction();

                        entity.MenuID = menuId;
                        entity.FunctionID = functionid;
                        entity.Sequence = i;

                        db.BasicMenuFunction.Added(entity);
                    }
                    else
                    {
                        entity.Sequence = i;

                        db.BasicMenuFunction.Modified(entity);
                    }

                }
            }

            return SaveAndResult("设置成功");
        }
    }
}